package com.ffapp.f9164.td.login;

import android.Manifest;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.BasisActivity;
import com.ffapp.f9164.td.basis.BasisApp;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.common.ObserverManager;
import com.ffapp.f9164.td.home.HomeTabActivity;
import com.ffapp.f9164.td.view.PopHandle;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.BleUtils;
import my.DialogUtils;
import my.MySharedPreferences;

public class LoginActivity extends BasisActivity {

    @BindView(R.id.btn_login)
    TextView mLoginBtn;
    //    private CheckBox mRePwdCb;
    private EditText mDeviceNameEt;
    private EditText mPwdEt;
    private BleDevice bleDevice;

    public static boolean isConnect = false;

    public static boolean isLogin = false;

    @BindView(R.id.img_check_pwd)
    ImageView img_check_pwd;

    private final int REQUEST_SERVER_CHOOSE = 14;
    public static final String KEY_DATA = "key_data";

    public static void toLoadingAllClear(Context mContext) {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }


    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.activity_login);

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)     //设置重连次数和重连时间间隔
                .setConnectOverTime(20000)      //设置连接超时
                .setOperateTimeout(5000);   //操作超时时间
        BleManager.getInstance().isSupportBle();

        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String deviceName = mDeviceNameEt.getText().toString().trim();
                if (TextUtils.isEmpty(deviceName)) {
                    showToast(R.string.device_empty);
                    return;
                }

                String password = mPwdEt.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    showToast(R.string.user_password_empty);
                    return;
                }
                blueToothConnect();
            }
        });

//        mRePwdCb = (CheckBox) findViewById(R.id.cb_pwd);
        mPwdEt = (EditText) findViewById(R.id.et_device_pwd);
        mDeviceNameEt = (EditText) findViewById(R.id.et_device_name);
        mDeviceNameEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityTool.skipActivityForResult(LoginActivity.this, SearchBlueToothActivity.class, REQUEST_SERVER_CHOOSE);
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        Acp.getInstance(mContext).request(new AcpOptions.Builder()
                        .setPermissions(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                        ).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        initReal();
                    }
                    @Override
                    public void onDenied(List<String> permissions) {
//                        BasisApp.showToast(permissions.toString() + "权限拒绝");
                        DialogUtils.DialogOKmsgFinish(mContext,"请在授权应用后重新启动app");
                    }
                });
    }

    public void initReal(){
        setCheckView();
        checkFiles();
    }

    private void checkFiles() {
        String file_media = Constants.DIR_UPDATE;
        File destDir = new File(file_media);
        if (!destDir.exists()) {// 判断文件夹是否存在
            destDir.mkdirs();
        }
    }
    //蓝牙连接
    public void blueToothConnect() {
        showLoading();
        BleUtils.connect(bleDevice,mContext,mPwdEt.getText().toString().trim(), new BleUtils.BleUtilLoginCallBack() {
            @Override
            public void isLogin(boolean isSuccess,String message) {
                dismissProgress();
                if(BleUtils.isCancel){
                    return;
                }
                isLogin = isSuccess;
                if(isLogin){
                    if (new MySharedPreferences(mContext).getRememberPwd()) {
                        getOrSetBlueToothDevice(bleDevice);
                        MySharedPreferences mSp = new MySharedPreferences(mContext);
                        mSp.putString(bleDevice.getDevice().getAddress(), mPwdEt.getText().toString().trim());
                    }
                    mDeviceNameEt.setText("");
                    mPwdEt.setText("");
                    ActivityTool.skipActivity(mContext, HomeTabActivity.class);
                }else {
                    showToast(""+message);
                }
            }
        });
    }


    private String getOrSetBlueToothDevice(BleDevice bleDevice) {
        MySharedPreferences mSp = new MySharedPreferences(this);
        if (TextUtils.isEmpty(mSp.getString(bleDevice.getDevice().getAddress()))) {
            mSp.putString(bleDevice.getDevice().getAddress(), mPwdEt.getText().toString().trim());
        } else {
            return mSp.getString(bleDevice.getDevice().getAddress());
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().disconnectAllDevice();
        BleManager.getInstance().destroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SERVER_CHOOSE && resultCode == REQUEST_SERVER_CHOOSE) {
            bleDevice = (BleDevice) data.getExtras().get("bleDevice");
            mDeviceNameEt.setText(TextUtils.isEmpty(bleDevice.getName()) ? "未知设备" : bleDevice.getName());
            if (!TextUtils.isEmpty(getOrSetBlueToothDevice(bleDevice))){
                mPwdEt.setText(getOrSetBlueToothDevice(bleDevice));
                new MySharedPreferences(mContext).putRememberPwd(true);
                setCheckView();
//                mRePwdCb.setChecked(true);
            }
        }

    }



    @OnClick(R.id.view_remember_pwd)
    void rememberPwd() {
        MySharedPreferences msp = new MySharedPreferences(mContext);
        msp.putRememberPwd(!msp.getRememberPwd());
        if (msp.getRememberPwd()) {
            msp.putRememberUser(true);
        }
        setCheckView();
    }

    void setCheckView() {
        MySharedPreferences msp = new MySharedPreferences(mContext);
        img_check_pwd.setImageResource(msp.getRememberPwd() ? R.drawable.login_icon_check_seleted : R.drawable.login_icon_check_unselected);
    }


    @Override
    protected void onResume() {
        isConnect = true;
        super.onResume();
    }
}
